package com.wjc.utils.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.wjc.hibernate.bean.User;

public class EmailUtil {

	private static Session getSession() {
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

		Authenticator authenticator = new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("jiachuanwang01@gmail.com", "s99263263");
			}

		};
		Session session = Session.getDefaultInstance(props, authenticator);
		return session;
	}

	public static void sendEmail(User user) {

		try {

			Message message = new MimeMessage(getSession());
			message.setFrom(new InternetAddress("jiachuanwang01@gmail.com"));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getEmail()));
			message.setSubject("Active your account");

			StringBuffer sb = new StringBuffer("Click to active your account</br>");
			sb.append("<a href=\"http://localhost:8080/ssh/user/activate.action?method=activate&email=");
			sb.append(user.getEmail());
			sb.append("&validateCode=");
			sb.append(user.getValidationCode());
			sb.append("\">active");
			sb.append("</a>");
			message.setText(sb.toString());
			Transport.send(message);

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
